import {
  getShopListByPool
} from "@/api/activeManage/active";

import {
  getUserListByIds
} from "@/api/userManage/user";

import {
  getServeTypeDict, buildOneselfServeList
} from "@/api/common/index";

import {
  exportOrientTemplate, exportRedPacketTemplate, exportGiveTemplate
} from "@/api/download";

import {
  addServe, editServe, delServe
} from "@/api/activeManage/serve";
import {isDecimal} from '@/utils/tools.js'

let tabFwList = [
  {label: '自建服务', name: 'zjfw', query: {type: 1}, list: []},
  {label: '官方服务', name: 'gffw', query: {}, list: []},
]
export default {
  name: "listData", 
  data() {
    return {
      probability: 0.5, //谢谢惠顾默认概率
      shopList: [], //商家列表
      searchProp: {
        loading: false,
        autoComplete: null, //搜索对象
        text: this.val,
        options: []
      }, 
      userList: [], //用户列表
      tabFwList: tabFwList,
      currentFwTab: tabFwList[0],
      checkedArr: [], //选中套餐
      sumsObj: {
        marketPrice: '0.00',
        preferentialPrice: '0.00',
        writeOffPrice: '0.00'
      },
      glfwProps: {
        queryGl: false,
        list: [],
        loading: false,
        total: 0,
        queryParams: {
          // pageNum: 1,
          // pageSize: 10,
          type: 1
        },
        dictTypeList: [],
      }
    };
  },
  computed: {
    tableData(){
      let list = [], { activityTypeId } = this.currentItem
      let item = {
        serveTypeId: '',
        id: '', 
        serveName: '谢谢惠顾',
        price: '0',
        writeOffFee: '0',
        itemNum: '0',
        probability: this.probability,
        discountedPrice: '0.00'
      }
      this.tabFwList.forEach(tab =>{
        list = [...list, ...tab.list]
      })
      let list_checked = list.filter(i => i.isChecked)
      list_checked.forEach(item => {
        this.$set(item, 'total', this.computedRowTotal(item))
        this.$set(item, 'scTotal', this.computedRowScTotal(item))
      })
      this.computedSums(list_checked)
      if(activityTypeId == 7){
        let idx = list_checked.findIndex(i => i.id == '-1')
        if(idx == -1){
          list_checked.push(item)
        }
      }
      return list_checked
    },
  },
  mounted(){
    this.getUserListByIds()
  },
  methods: {
    getUserListByIds(){
      let _self = this, {users, activeType} = this.$route.query
      if(!users || activeType != 5) return
      getUserListByIds(users).then(res => {
        _self.userList = res.data
      })
    },
    addUser(){
      let _self = this, {activityTypeId} = this.currentItem, row = {}
      if(activityTypeId == 6){
        row = {
          phone: '',
          name: '',
          licensePlate: '',
          insureCode: '',
          balance: '',
          phone_error: true,
          name_error: true,
        }
      }else if(activityTypeId == 2){
        row = {
          phone: '',
          name: '',
          licensePlate: '',
          phone_error: true,
          name_error: true,
          orderTimeStart: '',
          payValidDay: 1,
          orderPeriodValidity: 1,
          useStatus: 1,
        }
      }else{
        row = {
          phone: '',
          name: '',
          licensePlate: '',
          phone_error: true,
          name_error: true,
          useStatus: 1,
        }
      }
      _self.userList.push(row)
      _self.$set(_self.currentItem, 'acddUsers', _self.userList)
    },
    // 下载用户模板
    exportUserTmp(){
      let {activityTypeId} = this.currentItem, row = {}
      if(activityTypeId == 6){
        exportRedPacketTemplate({}, '用户模板')
      }else if(activityTypeId == 2){
        exportOrientTemplate({}, '用户模板')
      }else{
        exportGiveTemplate({}, '用户模板')
      }
    },
    importUser(){
      let dilogVm = this.$refs['importDialog']
      dilogVm.showDialog()
    },
    importSuccess(list){
      let _self = this, {activityTypeId} = this.currentItem
      _self.userList = [..._self.userList, ...list.map(i => {
        let obj = {
          id: i.id,
          name: i.name,
          phone: i.phone,
          licensePlate: i.licensePlate
        }
        if(activityTypeId == 6){
          obj.insureCode = i.insureCode
          obj.balance = i.balance
        }else if(activityTypeId == 2){
          obj.orderTimeStart = i.orderTimeStart || ''
          obj.payValidDay = i.payValidDay || 1
          obj.orderPeriodValidity = i.orderPeriodValidity || 1
          obj.useStatus =  1
        }else{
          obj.useStatus =  1
        }
        return obj
      })]
      _self.$set(_self.currentItem, 'acddUsers', _self.userList)
    },
    removeTargetUser(idx){
      let _self = this
      _self.userList.splice(idx, 1)
      _self.$set(_self.currentItem, 'acddUsers', _self.userList.map(i => i.id).join(','))
    },
    // 根据商户池获取商户列表
    async queryShopListByPool(key){
      if(key == 'change'){
        this.currentItem.suitShopIds = []
      }
      let isSuccess = false, _self = this, {shopPool = [], suitShopIds = []} = this.currentItem
      let ids = shopPool.join(',')
      if(ids == '') {
        _self.shopList = []
        _self.searchProp.options = _self.shopList
        isSuccess = true
      }else{
        await getShopListByPool(ids).then(res => {
          _self.shopList = res.data.map(item => {
            return {
              id: item.id,
              shopName: item.shopName,
              shopAddress: item.shopAddress,
              isChecked: suitShopIds.includes(`${item.id}`)
            }
          })
          _self.searchProp.options = _self.shopList
          isSuccess = true
        })
      }      
      return isSuccess
    },
    // 搜索
    remoteMethod(query) {
      let _self = this
      if (query !== '') {
        _self.searchProp.options = _self.shopList.filter(item => {
          let {shopName} = item
          return shopName && shopName.indexOf(query) > -1;
        });
      } else {
        _self.searchProp.options = _self.shopList;
      }
    },
    // 适用商户全选
    selectShopAll(boo){
      let _self = this
      _self.searchProp.options.forEach(i => {
        _self.$set(i, 'isChecked', boo)
      })
      let arr = _self.searchProp.options.filter(i => i.isChecked).map(i => i.id)
      _self.$set(_self.currentItem, 'suitShopIds', arr)
    },
    actionShopItem(item){
      let _self = this
      _self.$set(item, 'isChecked', !item.isChecked)
      let arr = _self.searchProp.options.filter(i => i.isChecked).map(i => i.id)
      let maxLen = _self.searchProp.options.length
      if(arr.length && maxLen == arr.length){
        _self.boo.shopAll = true
      } else {
        _self.boo.shopAll = false
      }
      _self.$set(_self.currentItem, 'suitShopIds', arr)
    },
    // 自建/官方服务
    getServeList(type = 'init'){
      let _self = this, { id } = this.currentItem
      if(type == 'init'){
        buildOneselfServeList({activeId: id, type: 1}).then(res => {
          let {data} = res, {serveTypeIds = []} = _self.currentItem
          _self.currentFwTab.list = data.map(i => {
            return {
              serveTypeId: i.serveTypeId,
              id: i.id,
              itemNum: i.itemNum,
              serveImg: i.serveImg,
              serveName: i.serveName,
              serveDetails: i.serveDetails,
              discountedPrice: i.discountedPrice,
              price: i.price,
              writeOffFee: i.writeOffFee,
              isChecked: serveTypeIds.includes(`${i.id}`),
              probability: i.probability || '0'
            }
          })
        })
        buildOneselfServeList({activeId: id}).then(res => {
          let {data} = res, {serveTypeIds = []} = _self.currentItem
          _self.tabFwList[1].list = data.map(i => {
            return {
              serveTypeId: i.serveTypeId,
              id: i.id,
              itemNum: i.itemNum,
              serveImg: i.serveImg,
              serveName: i.serveName,
              serveDetails: i.serveDetails,
              discountedPrice: i.discountedPrice,
              price: i.price,
              writeOffFee: i.writeOffFee,
              isChecked: serveTypeIds.includes(`${i.id}`),
              probability: i.probability || '0'
            }
          })
        })
      }else{
        buildOneselfServeList(_self.currentFwTab.query).then(res => {
          let {data} = res, {serveTypeIds = []} = _self.currentItem
          _self.currentFwTab.list = data.map(i => {
            return {
              serveTypeId: i.serveTypeId,
              id: i.id,
              itemNum: i.itemNum,
              serveImg: i.serveImg,
              serveName: i.serveName,
              serveDetails: i.serveDetails,
              discountedPrice: i.discountedPrice,
              price: i.price,
              writeOffFee: i.writeOffFee,
              isChecked: serveTypeIds.includes(`${i.id}`),
              probability: i.probability || '0'
            }
          })
        })
      }
    },
    tabFwChange(tab){
      let _self = this
      _self.currentFwTab = tab
      _self.getServeList('select')
    },
    validateFwNum(value){
      let reg = /^\d+$/
      if (!reg.test(value) || value == '0') return false
      return true
    },
    computedRowTotal(row){
      let total = parseFloat(row.writeOffFee)
      return total.toFixed(2)
    },
    computedRowScTotal(row){
      let total = parseFloat(row.price)
      return total.toFixed(2)
    },
    computedSums(list){
      let _self = this, obj = {marketPrice: '0.00', preferentialPrice: '0.00', writeOffPrice: '0.00'}
      list.forEach(item => {
        obj.writeOffPrice = parseFloat(obj.writeOffPrice) + parseFloat(item.total)
        obj.marketPrice = parseFloat(obj.marketPrice) + parseFloat(item.scTotal)
      })
      obj.preferentialPrice = parseFloat(obj.marketPrice) - parseFloat(obj.writeOffPrice)
      _self.sumsObj = {...obj}
    },
    actionFwItem(item){
      let _self = this, { activityTypeId } = this.currentItem
      if(activityTypeId == 4){ // 团购活动 -- 只能选一个服务
        _self.tabFwList.forEach(tab =>{
          tab.list.forEach(i => {
            _self.$set(i, 'isChecked', false)
          })
        })
      }
      _self.$set(item, 'isChecked', !item.isChecked)
      _self.$nextTick(() => {
        let ids = _self.tableData.map(i => i.id)
        _self.$set(_self.currentItem, 'serveTypeIds', ids)
      })
    },
    rowNumFwChange(e, row){
      let _self = this
      let {innerText} = e.target
      let boo = _self.validateFwNum(innerText)
      if(!boo) {
        _self.sumsObj = {
          scj: '--', yhj: '--', hxj: '--'
        }
        return _self.$message.error('请输入大于0的整数')
      }
      _self.$set(row, 'itemNum', innerText)
    },
    async getGlfwList(){
      let _self = this, isSuccess = false
      _self.glfwProps.loading = true
      await buildOneselfServeList(_self.glfwProps.queryParams).then(res => {
        // _self.glfwProps.list = res.rows || []
        // _self.glfwProps.total = res.total
        _self.glfwProps.list = res.data || []
        isSuccess = true
      })
      _self.glfwProps.loading = false
      return isSuccess
    },
    showFwDialog(){
      let _self = this
      _self.glfwProps.queryGl = true
      _self.$nextTick(async () => {
        let isSuccess = await _self.getGlfwList()
        if(isSuccess){
          _self.$refs['dialog-glfw'].showDialog = true
        }
        _self.glfwProps.queryGl = false
      })
    },
    // 获取每一页中的题目
    toTreeData(list){
      let arrTree = []
      let arrObj = list.reduce((acc, cur) => {
        // 如果不存在这个键，则设置它赋值 [] 空数组
        if (!acc[cur.serveTypeTwo]) {
          acc[cur.serveTypeTwo] = [];
        }
        cur.value = cur.id
        cur.label = cur.serveType
        acc[cur.serveTypeTwo].push(cur)
        return acc
      }, {})
      for(let key in arrObj){
        arrTree.push({
          value: key,
          label: key == '0' ? '服务' : '外部卡券',
          children: arrObj[key]
        })
      }
      return arrTree
    },
    /** 查询用户列表 */
    async queryServeTypeDict() {
      let _self = this, isSuccess = false
      await getServeTypeDict()
      .then((res) => {
        isSuccess = true
        let list = res.data.filter(i => i.serveTypeTwo == '0' && i.typeStatus == 1)
        _self.glfwProps.dictTypeList = _self.toTreeData(list)
      })
      return isSuccess
    },
    addFwItem(){
      let _self = this
      let item = {
        isEdit: true,
        serveTypeId: '',
        serveName: '',
        serveDetails: '',
        itemNum: '1',
        writeOffFee: '0.00',
        price: '0.00',
      }
      _self.glfwProps.list.unshift(item)
    },
    editFwItem(row){
      this.$set(row, 'isEdit', true)
    },
    async saveFwItem(row){
      let _self = this, {serveTypeId, serveName, serveDetails, itemNum, writeOffFee, price} = row
      let reg = /^\d+$/, apiFn = Function
      if(!serveTypeId) return _self.$message.error('服务类型不能为空')
      if(!serveName) return _self.$message.error('服务名称不能为空')
      if(!serveDetails) return _self.$message.error('服务明细不能为空')
      if(!reg.test(itemNum)) return _self.$message.error('请输入正确服务次数')
      if(!isDecimal(`${writeOffFee}`)) return _self.$message.error('请输入正确核销价')
      if(!isDecimal(`${price}`)) return _self.$message.error('请输入正确市场单价')
      let params = JSON.parse(JSON.stringify(row))
      params['serveTypeId'] = (row.serveTypeId || [])[1] || ''
      if(!row.id){
        apiFn = addServe
      }else {
        apiFn = editServe
      }
      _self.$set(row, 'isSave', true)
      await apiFn(params).then(res => {
        _self.$set(row, 'isEdit', false)
        // _self.$set(row, 'serveTypeId', serveTypeId)
        _self.getServeList()
        _self.getGlfwList()
      }).finally(() => {
        _self.$set(row, 'isSave', false)
      })
    },
    /** 删除按钮操作 */
    delFwItem(row, index) {
      let id = row.id, _self = this
      if(!id){
        _self.glfwProps.list.splice(index, 1)
      }else{
        this.$modal
        .confirm('是否确认删除？')
        .then(function () {
          return delServe(id);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          _self.getGlfwList()
          return _self.getServeList()
        })
        .catch(() => {});
      }
      
    },
  }
};